package org.example.rowing.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;

@Controller
@Slf4j
public class ChangePasswordController {
    @FXML
    public PasswordField currentPasswordField;
    @FXML
    public PasswordField newPasswordField;
    @FXML
    public PasswordField confirmPasswordField;
    @FXML
    public Label statusLabel;

    @Autowired
    private LoginService loginService;
    private String currentUsername;


    // 初始化当前用户（由登录控制器调用）
    public void initialize(String username) {
        this.currentUsername = username;
        clearFields();
    }

    @FXML
    private void handleSubmit() {
        String current = currentPasswordField.getText();
        String newPass = newPasswordField.getText();
        String confirm = confirmPasswordField.getText();

        if (!validateInputs(current, newPass, confirm)) {
            return;
        }

        if (loginService.changePassword(currentUsername, current, newPass)) {
            showSuccess();
            navigateToLogin();
        } else {
            showError("密码修改失败：原密码错误或新密码不符合要求");
        }
    }

    @FXML
    private void handleBackToLogin() {
        navigateToLogin();
    }

    private boolean validateInputs(String current, String newPass, String confirm) {
        if (current.isEmpty() || newPass.isEmpty() || confirm.isEmpty()) {
            showError("所有字段都必须填写");
            return false;
        }

        if (!newPass.equals(confirm)) {
            showError("新密码与确认密码不一致");
            return false;
        }

        if (current.equals(newPass)) {
            showError("新密码不能与旧密码相同");
            return false;
        }

        return true;
    }

    private void showSuccess() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("修改成功");
        alert.setHeaderText(null);
        alert.setContentText("密码已成功更新，请重新登录");
        alert.showAndWait();
    }

    private void showError(String message) {
        statusLabel.setStyle("-fx-text-fill: #e74c3c;");
        statusLabel.setText(message);
    }

    private void clearFields() {
        currentPasswordField.clear();
        newPasswordField.clear();
        confirmPasswordField.clear();
        statusLabel.setText("");
    }

    private void navigateToLogin() {
        try {
            Stage stage = (Stage) statusLabel.getScene().getWindow();
            NavigationUtil.navigateToScene(stage, "/fxml/LoginView.fxml", "赛艇赛事管理系统");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
